<template>
  <div class="login-page">
    <h1 class="page-title">光谷智慧交通系统管理平台</h1>
    <main class="login-main">
      <BaseCard
        v-model:formData="formData"
        v-bind="{ formRules, leftBtnText, disableTipLink, tiplinkText }"
        @submit="handleSubmit"
        @tipClick="handleRouterTo"
        ref="baseCard"
        class="login-card"
      >
        <template #card-header>
          <section class="card-header">
            <el-tabs v-model="userType" class="type-tabs">
              <el-tab-pane label="普通用户" name="common"></el-tab-pane>
              <el-tab-pane label="交管部门" name="department"></el-tab-pane>
              <el-tab-pane label="管理员" name="admin"></el-tab-pane>
            </el-tabs>
          </section>
        </template>
        <template #form-items>
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model.trim="formData.userName"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="loginPwd">
            <el-input
              type="password"
              v-model.trim="formData.loginPwd"
              placeholder="请输入密码"
              show-password
              :prefix-icon="Key"
              clearable
            ></el-input>
          </el-form-item>
        </template>
        <template #form-extra>
          <section class="password-operation">
            <div class="remember-password">
              <el-checkbox label="记住密码" v-model="rememberPassword"></el-checkbox>
            </div>
            <div class="forget-password">
              <el-link :disabled="disableTipLink">
                <router-link
                  :to="disableTipLink ? { name: 'login' } : { name: 'forget', query: { userType } }"
                >
                  忘记密码?
                </router-link>
              </el-link>
            </div>
          </section>
        </template>
      </BaseCard>
    </main>
    <ImageCaptcha v-model="showCaptcha" v-if="showCaptcha" @verified="handleLogin" />
  </div>
</template>

<script setup>
import { ref, watch, useTemplateRef, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { User, Key } from '@element-plus/icons-vue'
import { userLogin } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseCard from '@/components/LoginView/BaseCard.vue'
import ImageCaptcha from '@/components/LoginView/ImageCaptcha.vue'

const router = useRouter()
const baseCard = useTemplateRef('baseCard')

const userType = ref('common')
const rememberPassword = ref(false)
const localData = ref({
  common: null,
  department: null,
  admin: null,
})
const formData = ref({
  userName: '',
  loginPwd: '',
})
const formRules = ref({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 100, message: '用户名长度在1到100个字符', trigger: 'blur' },
  ],
  loginPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 100, message: '密码长度在1到100个字符', trigger: 'blur' },
  ],
})
const leftBtnText = ref('登录')
const tiplinkText = ref(`初次使用？点我注册`)
const showCaptcha = ref(false)

const disableTipLink = computed(() => {
  return userType.value !== 'common'
})

const handleSubmit = async () => {
  showCaptcha.value = true
  // 记住密码
  if (rememberPassword.value) {
    localStorage.setItem(
      `traffic-system-user-${userType.value}`,
      JSON.stringify({
        ...formData.value,
        userType: userType.value,
        rememberPassword: rememberPassword.value,
      }),
    )
  } else {
    localStorage.removeItem(`traffic-system-user-${userType.value}`)
  }
}
const handleLogin = async () => {
  try {
    await userLogin({ ...formData.value, userType: userType.value })
    ElMessage({
      message: '登录成功',
      type: 'success',
      showClose: true,
    })
    router.push({
      name: 'map',
      params: { userName: formData.value.userName },
      query: { userType: userType.value },
    })
  } catch (error) {
    switch (error.status) {
      case 400: {
        ElMessageBox.alert('用户名或密码错误', {
          confirmButtonText: '确定',
          type: 'error',
        })
        break
      }
      case 401: {
        ElMessageBox.alert('用户类型不匹配', {
          confirmButtonText: '确定',
          type: 'warning',
        })
        break
      }
      case 404: {
        ElMessageBox.confirm('用户名未注册,是否跳转到注册页面', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          callback: (action) => {
            switch (action) {
              case 'confirm':
                router.push({ name: 'register' })
                break
            }
          },
        })
        break
      }
    }
  }
}
const handleRouterTo = () => {
  router.push({ name: 'register' })
}

// 实现记住密码功能
// 当勾选记住密码时, 在登录成功后, 将用户名, 密码, 记住状态, 用户类型存入localStorage
// 当登录界面的用户类型和本地存储的类型一致时, 自动填充用户名, 密码和记住状态
// 若填充后, 用户类型发生变化, 则清空表单, 取消勾选记住密码
// 若在正确的页面填充后, 手动取消勾选记住密码, 则清空localStorage
const getLocalData = () => {
  for (const key in localData.value) {
    localData.value[key] = JSON.parse(localStorage.getItem(`traffic-system-user-${key}`))
  }
}
const autoFillForm = () => {
  if (!localData.value[`${userType.value}`]) {
    baseCard.value.resetForm()
    rememberPassword.value = false
    return
  }
  if (localData.value[`${userType.value}`].userType === userType.value) {
    formData.value.userName = localData.value[`${userType.value}`].userName
    formData.value.loginPwd = localData.value[`${userType.value}`].loginPwd
    rememberPassword.value = localData.value[`${userType.value}`].rememberPassword
  }
}

watch(userType, () => {
  baseCard.value.resetForm()
  getLocalData()
  autoFillForm()
})
watch(rememberPassword, () => {
  if (rememberPassword.value) return //这里只书写取消记住密码逻辑
  if (!localData.value[`${userType.value}`]) return
  if (localData.value[`${userType.value}`].userType === userType.value) {
    //当在正确的页面取消记住密码时, 自动清空localStorage和localData对应的值
    localStorage.removeItem(`traffic-system-user-${userType.value}`)
    localData.value[`${userType.value}`] = null
  }
})

onMounted(() => {
  getLocalData()
  autoFillForm()
})
</script>

<style lang="scss" scoped>
.login-page {
  position: relative;
  min-height: 100vh;
  background-image: url('img/背景2.gif');
  background-repeat: no-repeat;
  background-size: cover;
  .page-title {
    position: relative;
    top: 8rem;
    font-size: 2.5rem;
    color: #fff;
    text-align: center;
  }
  .login-main {
    position: absolute;
    top: 55%;
    left: 50%;
    width: 22rem;
    transform: translate(-50%, -50%);
    :deep(.login-card) {
      .card-header {
        .type-tabs {
          .el-tabs__content {
            display: none;
          }
          .el-tabs__header {
            margin-bottom: 0;
            .el-tabs__nav-wrap {
              &::after {
                content: unset;
              }
              .el-tabs__nav {
                width: 100%;
                .el-tabs__item {
                  flex: 1;
                  padding: unset;
                }
              }
            }
          }
        }
      }
      .password-operation {
        display: flex;
        justify-content: space-between;
        margin-top: 0.7rem;
        .forget-password {
          align-content: center;
          .el-link {
            display: block;
            a {
              text-decoration: none;
              color: inherit;
              cursor: inherit;
            }
          }
        }
      }
    }
  }
}
</style>
